import { login, logout, getInfo, guide } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import md5 from 'js-md5'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  guide: sessionStorage.getItem('guide'),
  info: sessionStorage.getItem('admin_info')
}

const mutations = {
  SET_GUIDE: (state, guide = 0) => {
    sessionStorage.setItem('guide', guide)
    state.guide = guide
  },
  SET_INFO: (state, info = '') => {
    if (info) {
      info = JSON.stringify(info)
      sessionStorage.setItem('admin_info', info)
    } else {
      sessionStorage.removeItem('admin_info')
    }
    state.info = info
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: md5(password) }).then(response => {
        const { status, code, data } = response
        if (status || code) {
          const token = (code !== 200) ? data.token : data.access_token
          // console.log(status, code, token)
          commit('SET_TOKEN', token)
          commit('SET_INFO', data)
          setToken(token)
        }
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(({ status, code, data }) => {
        if (status || code) {
          const { roles, name, avatar, introduction } = data
          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject('抱歉您还没有任何权限，请联系管理员赋予权限')
          }
          commit('SET_ROLES', roles)
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar || 'http://www.image.jswei.cn/avatar/avatar.png')
          commit('SET_INTRODUCTION', introduction)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  setGuide({ commit }, id) {
    guide(id).then(({ status, data }) => {
      if (status) {
        commit('SET_GUIDE', id)
      }
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_INFO', '')
        removeToken()
        resetRouter()
        resolve()
        sessionStorage.clear()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
